import React, { Component } from 'react';

import {user_login} from '../utils/api';
import {request_cancellist_collect,request_shoppcart_list } from '../store/actionCreator';
import {connect} from 'react-redux'
class Login extends Component {
    constructor(props){
        super(props);
        this.state = {
          phone:'',
          pass:''
        }
      }
      login(){
        if(this.state.phone&&this.state.pass){
            user_login(this.state).then((res)=>{
                if(res.data.code === 200){
                    console.log(res.data);
                    alert(res.data.msg)
                    //保存token
                    localStorage.setItem("token",res.data.token)
                    //保存用户资料
                    localStorage.setItem("userinfo",JSON.stringify(res.data.userinfo))
                    // 跳转到首页
                    this.props.history.push("/index");
                    //请求收藏列表
                    this.props.collectlist()
                    //请求购物车列表
                    this.props.shopcarlist()

                }else{
                    alert(res.data.msg)
                }
            })
        }
      }
    
      handleChange(e){
        //e表单元素的onChange事件的事件对象
        //e.currentTarget  表单元素
        //e.currentTarget.name  表单元素的value
        this.setState({
          [e.currentTarget.name]:e.currentTarget.value
        })
      }
    
    render() {
        console.log(this.props.shopcarlist[0]);
        return (
            <div>
                <div className='login-box'>
                    <div className='title'>登录页</div>
                    <div className="line">
                        <input type="text" placeholder='请输入账号' name='phone' defaultValue={ this.state.phone} onChange={(e)=>{this.handleChange(e)}}/>
                    </div>
                    <div className="line">
                        <input type="password" placeholder='请输入密码' name='pass' defaultValue={ this.state.pass} onChange={(e)=>{this.handleChange(e)}}/>
                    </div>
                    <div className="linee">
                        <input type="button" onClick={()=>{this.login()}} value="登录" />
                    </div>
                    <div onClick={()=>this.props.history.push('/reg')}>没有账号去注册</div>
                </div>
            </div>
        );
    }
}

export default connect(
    (state)=>{
        return{
            "shopcarlist":state.shopcarlist
        }
    },
    (dispath)=>{
        return{
            collectlist(){
                dispath(request_cancellist_collect());
                
            },
            shopcarlist(){
                dispath(request_shoppcart_list())
            }

        }
    }
)(Login);